package cn.chen.miaosha.service;

import cn.chen.miaosha.dao.GoodsDao;
import cn.chen.miaosha.domain.Goods;
import cn.chen.miaosha.domain.MiaoshaOrder;
import cn.chen.miaosha.domain.MiaoshaUser;
import cn.chen.miaosha.domain.OrderInfo;
import cn.chen.miaosha.redis.MiaoshaKey;
import cn.chen.miaosha.redis.RedisService;
import cn.chen.miaosha.util.MD5Util;
import cn.chen.miaosha.util.UUIDUtil;
import cn.chen.miaosha.vo.GoodsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class MiaoshaService {

    @Autowired
    GoodsService goodsService;

    @Autowired
    OrderService orderService;

    @Autowired
    RedisService redisService;

    @Transactional
    public OrderInfo miaosha(MiaoshaUser user, GoodsVO goods) {
        //减库存
        boolean success = goodsService.reduceStock(goods);
        //生成订单 写orderInfo
        if(success){
            return orderService.createOrder(user, goods);
        }else{
            setGoodsOver(goods.getId());
            return null;
        }
    }

    public long getMiaoshaResult(Long userId, Long goodsId) {
        MiaoshaOrder order = orderService.getMiaoshaOrderByUserIdGoodsId(userId, goodsId);
        if(order != null){
            return order.getOrderId();
        } else {
            boolean isOver = getGoodsOver(goodsId);
            if(isOver){
                return -1;
            } else {
                return 0;
            }
        }
    }

    public void setGoodsOver(Long goodsId) {
        redisService.set(MiaoshaKey.isGoodsOver, ""+goodsId, true);
    }

    private boolean getGoodsOver(Long goodsId) {
        return redisService.exists(MiaoshaKey.isGoodsOver, ""+goodsId);
    }

    public boolean checkPath(MiaoshaUser user, Long goodsId, String path) {
        if(user == null){
            return false;
        }
        String pathOld = redisService.get(MiaoshaKey.getMiaoshaPath, ""+user.getId()+""+goodsId,String.class);
        return path.equals(pathOld);
    }

    public String createMiaoshaPath(MiaoshaUser user, Long goodsId) {
        String str = MD5Util.md5(UUIDUtil.uuid() + "123456");
        redisService.set(MiaoshaKey.getMiaoshaPath, ""+user.getId() + goodsId, str);
        return str;
    }
}
